/*
* 生产记录详情
* */

import 'dart:convert';

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'dart:io';
import 'package:http_parser/http_parser.dart';
class ProductionRecordDetail extends StatefulWidget {
  @override
  _ProductionRecordDetailState createState() => _ProductionRecordDetailState();
}

class _ProductionRecordDetailState extends State<ProductionRecordDetail>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  var waterId = Go.Get.arguments;
  var workDetail = Map();
  var workFlow = [];
  List<Image> imgs = [];
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  List<Media> photos = [];
  List passPhoto = [];
  ImageForm.FormData formData;
  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    this.getWorkStageDetail();
  }

  /*
  * 获取详情
  * */
  getWorkStageDetail() async {
    var result = await getCompleteWorkStageDetail(waterId);
    if (result != null) {
      var image = result['attachments'].map<Image>((item){
        return Image.network(
          "${GlobalConfig.baseUrl}fs/irest/file/mps_fileTransferHandler/image?id=${item['attachmentId']}&ZJQFSESSION=${GlobalConfig.session}",
          fit: BoxFit.fill,
        );
      }).toList();
      this.setState(() {
        workDetail = result;
        workFlow = json.decode(result['formJson']??"[]");
        imgs = image;
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  getItemValue(item, items) {
    var result = '';
    for (var i = 0; i < items.length; i++) {
      if (item == items[i]['value']) {
        result = items[i]['label'];
        break;
      }
    }
    return result;
  }

  /*
  * 提交
  * */
  submit() async {
    var pass = {'id': waterId, 'attachments': this.passPhoto};
    var result = await appendWorkStage(pass);
    loading.dismiss();
    if (result != null && result == '') {
      Fluttertoast.showToast(msg: '提交完成');
      Go.Get.back();
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    if (this.photos.length > 0) {
      loading.show(delay: 30);
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = result;
        this.submit();
      }
    } else {
      loading.dismiss();
      Fluttertoast.showToast(msg: '请添加图片');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('生产记录详情'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(Styles.spacing8, Styles.spacing8,
                      Styles.spacing8, Styles.spacing8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing8, Styles.spacing8, Styles.spacing8),
                        alignment: Alignment.centerLeft,
                        color: Colors.white,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '已完成',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.MiddleFont17),
                            ),
                            Text(
                              '${workDetail['operator'] != null ? workDetail['operator'] : '--'} ${workDetail['create'] != null ? Utils.formatDateTimeToMinute(workDetail['create']) : '--'}',
                              style: TextStyle(
                                  color: Styles.LeftTitleColor,
                                  fontSize: Styles.NormalFont),
                            ),
                          ],
                        ),
                      ),
                      workFlow.length>0?Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing8, Styles.spacing8, Styles.spacing8),
                        color: Colors.white,
                        margin: EdgeInsets.fromLTRB(
                            0, Styles.spacing8, 0, Styles.spacing8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '检查项',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.Middle16Font),
                            ),
                            Column(
                              children: workFlow.map((item) {
                                return Container(
                                  child: Row(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        '检查项目: ${item['title']}',
                                        style: TextStyle(
                                            color: Styles.LeftTitleColor,
                                            fontSize: Styles.NormalFont13),
                                      ),
                                      Text(
                                        '${item['valueStr'] != null ? item['valueStr'] : '--'}',
                                        style: TextStyle(
                                            color: Styles.LeftTitleColor,
                                            fontSize: Styles.NormalFont13),
                                      ),
                                    ],
                                  ),
                                );
                              }).toList(),
                            ),
                          ],
                        ),
                      ):Container(),
                      Container(
                        padding: EdgeInsets.fromLTRB(Styles.spacing8,
                            Styles.spacing8, Styles.spacing8, Styles.spacing8),
                        color: Colors.white,
                        margin: EdgeInsets.fromLTRB(
                            0, Styles.spacing8, 0, Styles.spacing8),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '是否合格    ',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.Middle16Font),
                            ),
                            Text(
                              workDetail['qualified']!=null?(workDetail['qualified']?'合格':'不合格'):'--',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.Middle16Font),
                            ),
                          ],
                        ),
                      ),
                      imgs.length>0?Container(
                        color: Colors.white,
                        margin: EdgeInsets.fromLTRB(
                            0, Styles.spacing8, 0, Styles.spacing8),
                        height: 260.h,
                        child: Swiper(
                          itemBuilder: (BuildContext context, int index) {
                            //条目构建函数传入了index,根据index索引到特定图片
                            return imgs[index];
                          },
                          itemCount: imgs.length,
                          autoplay: false,
                          pagination: new SwiperPagination(), //这些都是控件默认写好的,直接用
                        ),
                      ):Container(),
                      Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, Styles.spacing8, 0, Styles.spacing8),
                        child: Text(
                          workDetail['remark']??'--',
                          style: TextStyle(
                              fontSize: Styles.NormalFont,
                              color: Styles.DetailColor),
                        ),
                      )
                    ],
                  ),
                ),
                imgs.length>=6?Container():Container(
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  color: Colors.white,
                  child: Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(
                            Styles.spacing16, Styles.spacing8, 0, 0),
                        child: Row(
                          children: <Widget>[
                            Text(
                              '工序照片补录(${this.photos.length}/${6-imgs.length})',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.MiddleFont17),
                            ),
                          ],
                        ),
                      ),
                      ImageSelectWidget(
                        maxNumber: 6-imgs.length,
                        onchange: (value) {
                          this.setState(() {
                            photos = value;
                          });
                        },
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: imgs.length>=6?Container():Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                showDialog(
                    barrierDismissible: false,
                    context: this.context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('确认提交吗？'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "取消",
                                style: TextStyle(color: Colors.black),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(color: Colors.red),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                                this.addImage();
                              },
                            ),
                          ),
                        ],
                      );
                    });
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '提交补录',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
